<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { queryStudentPaper } from "../api/sysStudentAnswerSheet/sysStudentAnswerSheet.ts";
import echarts, { type EChartsOption } from '../echart/echart.ts';

const route = useRoute()
const router = useRouter()
const id = ref(route.query.id as string);
const loading = ref(true)

const query = reactive({
  tesPaperId: ''
})

const studentRecords = ref<any[]>([])
const paperInfo = ref<{ tesPaperName: string; subject: string } | null>(null)

const getData = () => {
  if (!id.value) return;

  query.tesPaperId = id.value
  loading.value = true;

  queryStudentPaper(query).then(res => {
    if (res.data && res.data.length > 0) {
      studentRecords.value = res.data;
      paperInfo.value = {
        tesPaperName: res.data[0].tesPaperName,
        subject: res.data[0].subject
      };
      charData(); // 数据加载完成后调用 charData
    } else {
      studentRecords.value = [];
      paperInfo.value = null;
      ElMessage.warning('该试卷下暂无学生考试记录');
    }
  }).catch(err => {
    ElMessage.error('数据加载失败');
    console.error('API Error:', err);
  }).finally(() => {
    loading.value = false;
  })
}

const handleViewDetail = (row: any) => {
  console.log('查看详情:', row);
  ElMessage.info(`功能待开发：查看学生 ${row.studentName} 的答卷详情`);
}

onMounted(() => {
  if (!id.value) {
    ElMessageBox.alert('未获取到有效的试卷ID，将返回上一页。', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
    }).then(() => {
      router.back()
    }).catch(() => {
      router.back()
    })
  } else {
    getData()
  }
})

const studentNames = ref<string[]>([]);
const totalScores = ref<number[]>([]);

const charData = () => {
  studentNames.value = studentRecords.value.map(item => item.studentName);
  totalScores.value = studentRecords.value.map(item => item.totalScores);
  updateChart();
}

const chartContainer = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;

const option: EChartsOption = reactive({
  title: {
    text: '学生成绩'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['学生']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: studentNames.value
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '学生',
      type: 'bar',
      data: totalScores.value
    },
  ]
});

const updateChart = () => {
  if (myChart) {
    myChart.setOption({
      xAxis: {
        data: studentNames.value
      },
      series: [
        {
          data: totalScores.value
        }
      ]
    });
  }
}

onMounted(() => {
  if (chartContainer.value) {
    myChart = echarts.init(chartContainer.value);
    myChart.setOption(option);
  }
});

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
});
</script>

<template>
  <div v-if="!id" class="error-message">
    无法查看，无有效ID
  </div>
  <el-card v-loading="loading" v-else>
    <h4>学生成绩分析</h4>
    <el-divider />
    <el-tabs type="card">
      <el-tab-pane label="User">
        <el-row v-if="paperInfo">
          <el-col :span="2" style="align-items: center">
            <el-text size="large" class="mx-1" type="primary">试卷名称:</el-text>
          </el-col>
          <el-col :span="22">
            <p style="padding: 0;margin: 0;">{{ paperInfo.tesPaperName }}</p>
          </el-col>
        </el-row>

        <el-container>
          <el-main>
            <el-table
                :data="studentRecords"
                style="width: 100%; margin-top: 20px;"
                border
                stripe
            >
              <el-table-column type="index" label="序号" width="80" align="center" />
              <el-table-column prop="tesPaperName" label="试卷名称" width="150" align="center" />
              <el-table-column prop="subject" label="科目" width="120" align="center" />
              <el-table-column prop="studentName" label="学生姓名" width="120" align="center" />
              <el-table-column prop="objectiveTestScores" label="客观题得分" width="120" align="center" />
              <el-table-column prop="subjTestScores" label="主观题得分" width="120" align="center" />
              <el-table-column prop="totalScores" label="总得分" width="120" align="center" />
              <el-table-column prop="testStartTime" label="考试开始时间" width="220" align="center" />
              <el-table-column prop="endTime" label="考试结束时间" width="220" align="center" />
              <el-table-column prop="timeTaken" label="用时(秒)" width="100" align="center" />
              <el-table-column prop="id" label="考试ID" width="300px" align="center" show-overflow-tooltip />
            </el-table>
          </el-main>
        </el-container>
      </el-tab-pane>
      <el-tab-pane label="Config">
        <div style="display: flex;width: 100%;height: calc(100vh - 400px);justify-content: center;align-items: center;">
          <div ref="chartContainer" style="width: calc(100vw - 550px); height: calc(100vh - 450px);"></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<style scoped lang="scss">
.el-card {
  height: calc(100vh - 170px);
  overflow: auto;
}

.el-main{
  padding: 0;
  margin: 0;
}
</style>
